class Talk < ActiveRecord::Base
  has_many :users, :through => :user_talks
  has_many :user_talks, :dependent => :destroy
  
  has_many  :normal_talkers, 
            :through => :user_talks, :source => :user,
            :class_name => "User",
            :conditions => ['status = 0']
  has_many  :quit_talkers, 
            :through => :user_talks, :source => :user,
            :class_name => "User",
            :conditions => ['status = 1']
  
  has_many :talkees
  has_many :send_invitations, :class_name => 'Invitation', :foreign_key => 'talk_id'
  validates_presence_of :topic
  
  
#  attr_reader :lastest_update_at, :lasted_update_by
  
#  def initialize(talk)
#    @talk = talk
#    @lastest_update_at = @talk.updated_at
#    @lastest_update_by = @talk.created_by
#  end
  
  def latest_update_at
    if self.talkees.empty?
      self.updated_at
    else
      @talkee = self.talkees.find(:last)
      @talkee.updated_at
    end
  end
  
  def latest_update_by
    if self.talkees.empty?
      User.find(self.created_by)
    else
      @talkee = self.talkees.find(:last)
      @talkee.user
    end
  end
  
  def star(talk,user)
    @talk = talk
    @user = user
    @user_talk = UserTalk.find(:user_id => @user.id, :talk_id => @talk.id)
    @user_talk.star    
  end
end
